﻿using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
using Caliburn.Micro;
using Example.Frontend.Customers;
using Zero.Frontend;

namespace Example.Frontend.Shell
{
    [Export(typeof(IShell))]
    [Export(typeof(IBusyService))]
    public class ShellViewModel : Conductor<IChild>.Collection.OneActive, IShell, IBusyService
    {
        static ShellViewModel()
        {
            // add AdornerDecoratof to default template. This is fix for disapearing validation adorners.

            ConventionManager.DefaultItemTemplate = (DataTemplate)
                                        XamlReader.Parse(

                                            "<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
                                            "xmlns:cal='clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro'> " +
                                            "<AdornerDecorator>" +
                                            "<ContentControl cal:View.Model=\"{Binding}\" VerticalContentAlignment=\"Stretch\" HorizontalContentAlignment=\"Stretch\" />" +
                                            "</AdornerDecorator>" +
                                            "</DataTemplate>"
                                            );
        }

        private readonly CustomersViewModel _customers;

        [ImportingConstructor]
        public ShellViewModel(CustomersViewModel customers)
        {
            _customers = customers;

            Items.Add(_customers);

            DisplayName = "Example application";
        }

        protected override void OnInitialize()
        {
            base.OnInitialize();

            ActivateItem(Items.FirstOrDefault());
        }

        #region IBusyService

        public void MarkAsBusy(object sourceViewModel, object busyViewModel)
        {
            IsBusy = true;
        }

        public void MarkAsNotBusy(object sourceViewModel)
        {
            IsBusy = false;
        }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (_isBusy == value) return;
                
                _isBusy = value;

                NotifyOfPropertyChange(() => IsBusy);
            }
        }

        #endregion
    }
}
